﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;

namespace StyleCopMaker.StyleCopMaker
{
    public class StyleCopSettings
    {
        public string SettingsFile { get; private set; }

        public string CompanyName { get; set; }

        public string Copyright { get; set; }

        public StyleCopSettings(string settingsFile)
        {
            this.SettingsFile = settingsFile;

            XmlDocument document = new XmlDocument();
            document.Load(settingsFile);

            // TODO : StyleCop 4.5 Microsoft.StyleCop.CSharp.DocumentationRules to StyleCop.CSharp.DocumentationRules
            foreach (XmlElement node in document.SelectNodes("//Analyzer[@AnalyzerId='Microsoft.StyleCop.CSharp.DocumentationRules']//StringProperty"))
            {
                if (node.Attributes["Name"].Value == "CompanyName")
                {
                    this.CompanyName = node.InnerText;
                }
                else if (node.Attributes["Name"].Value == "Copyright")
                {
                    this.Copyright = node.InnerText;
                }
            }
        }

        public static StyleCopSettings GetSettings(string fileName)
        {
            FileInfo fi = new FileInfo(fileName);

            return GetSettings(fi.Directory);
        }

        private static StyleCopSettings GetSettings(DirectoryInfo directoryInfo)
        {
            if (directoryInfo.Parent == null)
            {
                return null;
            }

            string settingsFile = Path.Combine(directoryInfo.FullName, "Settings.StyleCop");
            if (File.Exists(settingsFile))
            {
                return new StyleCopSettings(settingsFile);
            }
            else
            {
                return GetSettings(directoryInfo.Parent);
            }
        }
    }
}
